function addMoreConditions(evt) {
  var elem = evt.target;
  if (elem.value != ')' && elem.value != '.') { // do not add another row for empty option or ending bracket.
    // remove the onChange event handler from previous conjunc dropdown
    jQuery(elem).unbind('change');
    // remove the empty option from previous conjunc dropdown
    elem.remove(0);

    var cond = jQuery('#divSearchContainer').clone();
    
    (cond.find('select[name=col]')[0]).selectedIndex = 0;
    (cond.find('select[name=compOpt]')[0]).selectedIndex = 0;

    // Add the empty option to the new conjunc dropdown
    var $conjunc = cond.find('select[name=conjunc]');
    $conjunc.change(addMoreConditions);
    $conjunc.prepend(jQuery("<option></option>").attr('value', '.').attr('selected', 'selected').text(''));
    ($conjunc[0]).selectedIndex = 0;
    cond.attr('id', '');
    cond.find('input').val('');

    cond.append(closeBtnHTML('removeCondition'));
    cond.find('a').click(removeCondition);

    jQuery('#divSearchUIPlaceholder').append(cond);
  }
}

function removeCondition(evt) {
  var $curr_conjunc = jQuery(evt.currentTarget);
  var $elem = $curr_conjunc.parent();

  if ($elem.nextAll().length == 0) {
    var $conjunc;
    if (jQuery('#divSearchUIPlaceholder').children().length == 1) {
      $conjunc = jQuery('#divSearchContainer').find('select[name=conjunc]');
    }
    else {
      $conjunc = $elem.prev().find('select[name=conjunc]');
    }
    $conjunc.change(addMoreConditions);
    $conjunc.prepend(jQuery("<option></option>").attr('value', '.').attr('selected', 'selected').text(''));
    ($conjunc[0]).selectedIndex = 0;
  }
  $elem.remove();

  return false;
}

function closeBtnHTML(cls) {
  var closebtnhtml = '';
  closebtnhtml += '<a href="#" class="' + cls + '" role="button" unselectable="on">';
  closebtnhtml += '  <span class="ui-icon ui-icon-closethick" unselectable="on" style="-moz-user-select: none;">close</span>';
  closebtnhtml += '</a>';
  return closebtnhtml;
}

function performSearch() {
  clearMessages();
  jQuery('#divAdvancedSearchResults').html('');
  jQuery('#divAdvancedSearchResults').addClass('divLoading');

  var cols = jQuery('#divSearchUI select[name=col]');
  var compOpts = jQuery('#divSearchUI select[name=compOpt]');
  var txtKeywords = jQuery('#divSearchUI input[name=txtKeyword]');
  var conjuncs = jQuery('#divSearchUI select[name=conjunc]');

  var err = [];
  var atlst1TextGiven = false;
  var len = txtKeywords.length;
  for (var i = 0; i < len; i++) {
    if (txtKeywords[i].value != '') {
      atlst1TextGiven = true;
    }
    if (compOpts[i].value != 'is' && txtKeywords[i].value == '') {
      var col = cols[i];
      var opt = compOpts[i];
      err.push('"' + col.options[col.selectedIndex].text + ' ' + opt.options[opt.selectedIndex].text + '" keyword cannot be empty');
    }
  }

  if (atlst1TextGiven == false) {
    displayMessage('error', 'Specify atleast one value for search');
    jQuery('#divAdvancedSearchResults').removeClass('divLoading');
    return;
  }

  if (err.length > 0) {
    if (err.length > 1) {
      displayMessage('error', '<ul>' + err.join('<li>') + '</ul>');
    }
    else {
      displayMessage('error', err[0]);
    }
    jQuery('#divAdvancedSearchResults').removeClass('divLoading');
    return;
  }

  var query_cond_arr = [];

  var len = cols.length;
  var query_cond = '';

  for (var i = 0; i < len; i++) {
    data = new Object();
    data.col = cols[i].value;
    data.opt = compOpts[i].value;
    data.keyword = txtKeywords[i].value;
    data.conjunc = conjuncs[i].value;

    query_cond_arr.push(data);
    query_cond += data.col + ' ' + data.opt + ' ' + data.keyword + ' ' + data.conjunc + ' ';
  }

  // Check if there is bracket mismatch
  if(query_cond.split('(').length != query_cond.split(')').length) {
    displayMessage('error', 'Search options are malformed. Please ensure each "(" has a corresponding ")"');
    jQuery('#divAdvancedSearchResults').removeClass('divLoading');
    return;
  }

  var data = new Object();
  data.conditions = query_cond_arr;
  var obj = new Object();
  obj.action = 'performAdvancedSearch';
  obj.params = data;
  var json_data = JSON.stringify(obj);

  var url = Drupal.settings.basePath + 'observation/data';
  jQuery.get(
    url,
    {request: json_data},
    function(data) {
      jQuery('#divAdvancedSearchResults').removeClass('divLoading');
      if (parseInt(data.error) == 1) {
        displayMessage('error', data.msg);
        return;
      } else {
        /*
        url = Drupal.settings.basePath + 'observation/' + data.observation_id;
        window.location.replace(url);
        */
        jQuery('#divAdvancedSearchResults').html(data.result);
        jQuery('.search_results').dataTable();
      }
    },
    'json'
  );
}

jQuery(document).ready(function() {
  jQuery('#btnSearch').click(performSearch);

  var $conjunc = jQuery('select[name=conjunc]');
  var len = $conjunc.length;
  ($conjunc[len - 1]).selectedIndex = 0;
  $conjunc.change(addMoreConditions);

});